// router.js
import {
	RouterMount,
	createRouter
} from 'uni-simple-router';
import commonApi from "@/services/api/common.js";
const IOSXJPluginIOSPhotoModel = uni.requireNativePlugin("IOSXJPlugin-IOSPhotoModel")
import $store from '@/store/index.js';
const router = createRouter({
	encodeURI: false,
	platform: process.env.VUE_APP_PLATFORM,
	APP:{
		registerLoadingPage: false,
		animation:{
			animationType:'fade-in'
		}
	},
	routes: [...ROUTES]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
	next();
});
// 全局路由后置守卫
router.afterEach((to, from) => {
	if(to.path == "/pages/start/index"){
		uni.getNetworkType({
			success: (e) => {
				if(e.networkType != 'none'){
					init()
				}else{
					uni.showLoading({ 
						title:getApp().$t("loadding.title.waitNetwork")
					})
					uni.onNetworkStatusChange((res)=>{
						if(res.isConnected){
							uni.hideLoading()
							init()
						}
					})
				}
			}
		})
		
	}
	console.log('跳转结束')
})

async function init() {
	try{
		await uni.$config.getConfigRequest()
		if(!uni.$config.plat_status){
			uni.showModal({
				title:'提示',
				content:'平台已关闭',
				showCancel:false,
				success:(e)=>{
					plus.runtime.quit();
				}
			})
			return
		}
	}catch(e){
		console.log(e);
		uni.showToast({
			icon:'none',
			title: e
		});
		return
	}
	try{
		await commonApi.appUpdate(0)
	}catch(e){
		//TODO handle the exception
	}
	//获取设备信息
	await getDeviceInfo()
	
	try{ 
		await $store.dispatch('initLogin')
		router.pushTab({
			name: 'index'
		});
	}catch(e){
		if(uni.$config.is_reg){
			router.replaceAll({
				name: 'login'
			});
		}else{
			await $store.dispatch('autoLogin')
			router.pushTab({
				name: 'index'
			});
		}
	}
}

async function getDeviceInfo(){
	let systemInfo = uni.getSystemInfoSync()
	var timeZoneOffset = new Date().getTimezoneOffset();
	var timeZone = "GMT" + (timeZoneOffset > 0 ? "-" : "+") + 
	              Math.floor(Math.abs(timeZoneOffset) / 60) + 
	              ":" + (Math.abs(timeZoneOffset) % 60);
	//获取设备详情
	let fromdata = {
		plat_code: uni.$config.plat_code,
		parent_code: uni.getStorageSync('parent_code') || '0',
		device_type: systemInfo.deviceType,
		device_os: systemInfo.osName,
		device_model: systemInfo.deviceBrand + ' ' + systemInfo.deviceModel,
		device_token: '',
		device_id:'',
		browser_name: systemInfo.browserName,
		browser_version: systemInfo.browserVersion,
		device_language: systemInfo.osLanguage,
		device_timezone: timeZone,
	}
	try {
		// 使用Promise封装异步操作，确保获取到设备信息后再提交
		fromdata.device_id = await new Promise((resolve, reject) => {
			IOSXJPluginIOSPhotoModel.getUDID((id) => {
				if (id) {
					resolve(id);
				} else {
					resolve('');
				}
			});
		});
		fromdata.device_token = fromdata.device_id; // 同步设置device_token

	} catch (e) {
		console.error('获取设备信息失败', e);
	}
	$store.commit('setDeviceInfo',fromdata)
}
export {
	router,
	RouterMount
}
